package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.admin.categorypojo.Category;
import com.itheima.admin.categorypojo.dto.CategoryDto;
import com.itheima.admin.categorypojo.vo.CategoryVo;
import com.itheima.common.JsonResult;
import com.itheima.admin.AdminPage;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wuzhiyong
 */
@RestController
@RequestMapping(value = "/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    /**
     * 新增
     *
     * @param categoryDto categoryDto
     * @return JsonResult
     */
    @PostMapping
    public JsonResult<Object> categoryAdd(@RequestBody CategoryDto categoryDto) {
        return categoryService.addCategory(categoryDto) ? JsonResult.success(null, "添加成功") : JsonResult.error("分类名已存在");
    }

    /**
     * 分页查询
     *
     * @param page     页
     * @param pageSize 页数
     * @return JsonResult
     */
    @GetMapping(value = "/page")
    public JsonResult<AdminPage<CategoryVo>> categoryPage(@RequestParam(value = "page") Integer page, @RequestParam(value = "pageSize") Integer pageSize) {
        AdminPage<CategoryVo> selectpage = categoryService.getPageCategory(page, pageSize);
        if (selectpage==null){
            return JsonResult.error("暂无数据");
        }
        return JsonResult.success(selectpage, null);
    }

    /**
     * 删除
     *
     * @param id id
     * @return JsonResult
     */
    @DeleteMapping
    public JsonResult<Object> categoryRemove(@RequestParam(value = "id") String id) {
        return categoryService.removeByIdCategory(id) ? JsonResult.success(null, "删除成功") : JsonResult.error("当前分类下关联了套餐，不能删除");
    }

    /**
     * 编辑
     *
     * @param categoryDto categoryDto
     * @return JsonResult
     */
    @PutMapping
    public JsonResult<String> categoryModify(@RequestBody CategoryDto categoryDto) {
        return categoryService.modifyByIdCategory(categoryDto) ? JsonResult.success("修改分类信息成功", null) : JsonResult.error("修改分类信息失败");
    }

    /**
     * 分类下拉列表
     *
     * @param type type
     * @return JsonResult
     */
    @GetMapping(value = "list")
    public JsonResult<List<Category>> categoryList(@RequestParam(value = "type") Integer type) {
        List<Category> categories = categoryService.getByTypeCategory(type);
        if (categories != null) {
            return JsonResult.success(categories, null);
        }
        return JsonResult.error("暂无数据");
    }

}
